package com.lfz.search.rabbit;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.lfz.common.vo.SysResult;
import com.lfz.search.pojo.JobItem;
import com.lfz.search.service.JobItemService;
import com.lfz.search.service.SearchService;
import com.lfz.search.vo.Page;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;

import java.io.IOException;

import static com.lfz.search.config.Constant.MAPPER;

@Component
public class AsyncTask {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private JobItemService jobItemService;

    @Autowired
    private SearchService searchService;

    /**
     * 向es中添加JobItem
     * @param message JobItem对象的json字符串
     * @return
     */
    @Async
    public ListenableFuture<String> PutJobItemOperation(String message) {

        SysResult result = null;
        try {
            JobItem jobItem = MAPPER.readValue(message, JobItem.class);
            // es添加文档
            jobItemService.addDocument(jobItem);
            result = SysResult.OK;
        } catch (Exception e) {
            e.printStackTrace();
            result = SysResult.OPERATE_FAILED;
            result.setData(ExceptionUtils.getStackTrace(e));
        }
        String json = null;
        try {
            json = MAPPER.writeValueAsString(result);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return new AsyncResult<>(json);
    }

    /**
     * 从RabbitMQ队列中接收其它系统的搜索请求
     * @param message Page对象的json字符串
     * @return
     */
    @Async
    public ListenableFuture<String> searchJobItemOperation(String message) {
        String json = null;
        SysResult result;
        try {
            Page page = MAPPER.readValue(message, Page.class);
            page = searchService.search(page);
            result = SysResult.oK(page);
        } catch (IOException e) {
            e.printStackTrace();
            result = SysResult.OPERATE_FAILED;
            result.setData(ExceptionUtils.getStackTrace(e));
        }

        try {
            json = MAPPER.writeValueAsString(result);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return new AsyncResult<>(json);
    }
}